<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>宠物商城管理系统</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .gradient-bg {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .hidden {
            display: none;
        }
        .sidebar {
            width: 280px;
            transition: all 0.3s;
            box-shadow: 4px 0 10px rgba(0, 0, 0, 0.1);
        }
        .main-content {
            margin-left: 280px;
            transition: all 0.3s;
            background-color: #f8fafc;
        }
        .card {
            transition: transform 0.2s, box-shadow 0.2s;
        }
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
        }
        .nav-item {
            transition: all 0.3s;
            border-radius: 8px;
            margin: 4px 0;
        }
        .nav-item:hover {
            background-color: rgba(255, 255, 255, 0.1);
            transform: translateX(5px);
        }
        .nav-item.active {
            background-color: rgba(255, 255, 255, 0.2);
        }
        .login-card {
            backdrop-filter: blur(10px);
            background-color: rgba(255, 255, 255, 0.95);
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
        }
        .stat-card {
            background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
            border: 1px solid rgba(0, 0, 0, 0.05);
        }
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            transition: all 0.3s;
        }
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        .table-container {
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            border-radius: 10px;
            overflow: hidden;
        }
        .table-header {
            background: linear-gradient(135deg, #f8fafc 0%, #edf2f7 100%);
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .fade-in {
            animation: fadeIn 0.3s ease-out;
        }
        .input-group {
            position: relative;
            margin-bottom: 1.5rem;
        }
        .input-group input {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            transition: all 0.3s;
            background-color: #f8fafc;
            font-size: 1.25rem;
        }
        .input-group input:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
            outline: none;
        }
        .input-group label {
            position: absolute;
            left: 1rem;
            top: 0.75rem;
            color: #718096;
            transition: all 0.3s;
            pointer-events: none;
        }
        .input-group input:focus + label,
        .input-group input:not(:placeholder-shown) + label {
            transform: translateY(-1.5rem);
            font-size: 0.875rem;
            color: #667eea;
        }
        .slide-fade-enter {
            opacity: 0;
            transform: translateX(30px);
        }
        .slide-fade-enter-active {
            transition: all 0.3s ease-out;
        }
        .slide-fade-leave-active {
            transition: all 0.3s ease-in;
            opacity: 0;
            transform: translateX(-30px);
        }
    </style>
</head>
<body class="bg-gray-100">
    <!-- 登录页面 -->
    <div id="loginPage" class="min-h-screen gradient-bg flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
        <div class="max-w-md w-full">
            <div class="login-card rounded-2xl p-8">
                <div class="text-center">
                    <i class="fas fa-paw text-6xl text-indigo-600 mb-4"></i>
                    <h2 class="text-3xl font-extrabold text-gray-900 mb-2">
                        宠物商城管理系统
                    </h2>
                </div>
                <form class="mt-8 space-y-6" onsubmit="handleLogin(event)">
                    <div class="space-y-4">
                        <div class="input-group">
                            <input id="username" name="username" type="text" required placeholder="用户名" class="text-center" value="1">
                        </div>
                        <div class="input-group">
                            <input id="password" name="password" type="password" required placeholder="密码" class="text-center" value="1">
                        </div>
                    </div>

                    <div>
                        <button type="submit" class="btn-primary group relative w-full flex justify-center py-3 px-4 border border-transparent text-lg font-medium rounded-lg text-white focus:outline-none">
                            <i class="fas fa-sign-in-alt mr-2"></i>
                            登录系统
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 主系统界面 -->
    <div id="mainPage" class="hidden">
        <!-- 侧边栏 -->
        <aside class="sidebar fixed top-0 left-0 h-full bg-gray-900 text-white">
            <div class="p-6">
                <div class="flex items-center space-x-3 mb-10">
                    <i class="fas fa-paw text-3xl text-indigo-400"></i>
                    <h1 class="text-xl font-bold">宠物商城管理系统</h1>
                </div>
                <nav class="space-y-1">
                    <a href="#" class="nav-item flex items-center px-4 py-3 text-gray-300 hover:text-white" data-page="dashboard">
                        <i class="fas fa-chart-line w-6"></i>
                        <span class="ml-3">控制台</span>
                    </a>
                    <a href="#" class="nav-item flex items-center px-4 py-3 text-gray-300 hover:text-white" data-page="pets">
                        <i class="fas fa-dog w-6"></i>
                        <span class="ml-3">宠物管理</span>
                    </a>
                    <a href="#" class="nav-item flex items-center px-4 py-3 text-gray-300 hover:text-white" data-page="products">
                        <i class="fas fa-box w-6"></i>
                        <span class="ml-3">商品管理</span>
                    </a>
                    <a href="#" class="nav-item flex items-center px-4 py-3 text-gray-300 hover:text-white" data-page="cart">
                        <i class="fas fa-shopping-cart w-6"></i>
                        <span class="ml-3">购物车</span>
                    </a>
                    <a href="#" class="nav-item flex items-center px-4 py-3 text-gray-300 hover:text-white" data-page="orders">
                        <i class="fas fa-clipboard-list w-6"></i>
                        <span class="ml-3">订单管理</span>
                    </a>
                </nav>
            </div>
            <div class="absolute bottom-0 left-0 right-0 p-6">
                <button id="logoutBtn" class="w-full flex items-center justify-center px-4 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors">
                    <i class="fas fa-sign-out-alt mr-2"></i>
                    退出登录
                </button>
            </div>
        </aside>

        <!-- 主要内容区域 -->
        <main class="main-content min-h-screen p-8">
            <!-- 控制台页面 -->
            <div id="dashboardPage" class="page-content fade-in">
                <div class="flex items-center justify-between mb-8">
                    <h2 class="text-2xl font-bold text-gray-800">控制台概览</h2>
                    <div class="text-sm text-gray-600">
                        <i class="far fa-clock mr-1"></i>
                        最后更新: <span id="lastUpdate">刚刚</span>
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                    <div class="stat-card rounded-xl p-6 card">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm font-medium text-gray-600 mb-1">总订单数</p>
                                <h3 class="text-3xl font-bold text-blue-600">0</h3>
                            </div>
                            <div class="p-3 bg-blue-100 rounded-full">
                                <i class="fas fa-shopping-bag text-blue-600 text-xl"></i>
                            </div>
                        </div>
                        <p class="text-sm text-gray-500 mt-2">
                            <i class="fas fa-arrow-up text-green-500 mr-1"></i>
                            较上月增长 12%
                        </p>
                    </div>
                    <div class="stat-card rounded-xl p-6 card">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm font-medium text-gray-600 mb-1">总销售额</p>
                                <h3 class="text-3xl font-bold text-green-600">¥0</h3>
                            </div>
                            <div class="p-3 bg-green-100 rounded-full">
                                <i class="fas fa-yuan-sign text-green-600 text-xl"></i>
                            </div>
                        </div>
                        <p class="text-sm text-gray-500 mt-2">
                            <i class="fas fa-arrow-up text-green-500 mr-1"></i>
                            较上月增长 8%
                        </p>
                    </div>
                    <div class="stat-card rounded-xl p-6 card">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm font-medium text-gray-600 mb-1">宠物数量</p>
                                <h3 class="text-3xl font-bold text-purple-600">0</h3>
                            </div>
                            <div class="p-3 bg-purple-100 rounded-full">
                                <i class="fas fa-paw text-purple-600 text-xl"></i>
                            </div>
                        </div>
                        <p class="text-sm text-gray-500 mt-2">
                            <i class="fas fa-arrow-up text-green-500 mr-1"></i>
                            较上月增长 5%
                        </p>
                    </div>
                    <div class="stat-card rounded-xl p-6 card">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm font-medium text-gray-600 mb-1">商品数量</p>
                                <h3 class="text-3xl font-bold text-yellow-600">0</h3>
                            </div>
                            <div class="p-3 bg-yellow-100 rounded-full">
                                <i class="fas fa-box text-yellow-600 text-xl"></i>
                            </div>
                        </div>
                        <p class="text-sm text-gray-500 mt-2">
                            <i class="fas fa-arrow-up text-green-500 mr-1"></i>
                            较上月增长 15%
                        </p>
                    </div>
                </div>

                <!-- 图表区域 -->
                <div class="mt-8 grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <div class="bg-white rounded-xl p-6 card">
                        <h3 class="text-lg font-semibold text-gray-800 mb-4">销售趋势</h3>
                        <div class="h-64 bg-gray-50 rounded-lg flex items-center justify-center">
                            <p class="text-gray-500">图表区域</p>
                        </div>
                    </div>
                    <div class="bg-white rounded-xl p-6 card">
                        <h3 class="text-lg font-semibold text-gray-800 mb-4">热门商品</h3>
                        <div class="h-64 bg-gray-50 rounded-lg flex items-center justify-center">
                            <p class="text-gray-500">图表区域</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 宠物管理页面 -->
            <div id="petsPage" class="page-content hidden fade-in">
                <div class="flex justify-between items-center mb-6">
                    <div>
                        <h2 class="text-2xl font-bold text-gray-800">宠物管理</h2>
                        <p class="text-gray-600 mt-1">管理所有可供销售的宠物</p>
                    </div>
                    <button class="btn-primary px-6 py-2 rounded-lg text-white flex items-center" onclick="showAddPetModal()">
                        <i class="fas fa-plus mr-2"></i>
                        添加宠物
                    </button>
                </div>
                <div class="bg-white rounded-xl shadow-sm overflow-hidden table-container">
                    <div class="p-4 table-header">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center space-x-4">
                                <div class="relative">
                                    <input type="text" placeholder="搜索宠物..." class="pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:border-indigo-500">
                                    <i class="fas fa-search absolute left-3 top-3 text-gray-400"></i>
                                </div>
                                <select class="border rounded-lg px-4 py-2 focus:outline-none focus:border-indigo-500">
                                    <option>所有类型</option>
                                    <option>猫咪</option>
                                    <option>狗狗</option>
                                    <option>其他</option>
                                </select>
                            </div>
                            <div class="flex items-center space-x-2">
                                <button class="px-4 py-2 text-gray-600 hover:text-gray-900">
                                    <i class="fas fa-filter mr-1"></i>
                                    筛选
                                </button>
                                <button class="px-4 py-2 text-gray-600 hover:text-gray-900">
                                    <i class="fas fa-sort mr-1"></i>
                                    排序
                                </button>
                            </div>
                        </div>
                    </div>
                    <table class="min-w-full">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">名称</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类型</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">价格</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                            </tr>
                        </thead>
                        <tbody id="petsTableBody" class="bg-white divide-y divide-gray-200">
                            <!-- 宠物列表将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                    <div class="p-4 border-t flex items-center justify-between">
                        <div class="text-gray-600 text-sm">
                            显示 1-10 条，共 50 条
                        </div>
                        <div class="flex items-center space-x-2">
                            <button class="px-3 py-1 border rounded hover:bg-gray-50">上一页</button>
                            <button class="px-3 py-1 bg-indigo-600 text-white rounded">1</button>
                            <button class="px-3 py-1 border rounded hover:bg-gray-50">2</button>
                            <button class="px-3 py-1 border rounded hover:bg-gray-50">3</button>
                            <button class="px-3 py-1 border rounded hover:bg-gray-50">下一页</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 商品管理页面 -->
            <div id="productsPage" class="page-content hidden fade-in">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-2xl font-bold">商品管理</h2>
                    <button class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600" onclick="showAddProductModal()">
                        添加商品
                    </button>
                </div>
                <div class="bg-white rounded-lg shadow overflow-hidden">
                    <table class="min-w-full">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">名称</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">价格</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">库存</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                            </tr>
                        </thead>
                        <tbody id="productsTableBody" class="bg-white divide-y divide-gray-200">
                            <!-- 商品列表将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 购物车页面 -->
            <div id="cartPage" class="page-content hidden fade-in">
                <div class="flex justify-between items-center mb-6">
                    <div>
                        <h2 class="text-2xl font-bold text-gray-800">购物车</h2>
                        <p class="text-gray-600 mt-1">管理您的购物车商品</p>
                    </div>
                </div>
                <div class="bg-white rounded-xl shadow-sm overflow-hidden p-6">
                    <div id="cartItems" class="divide-y divide-gray-200">
                        <!-- 购物车项目将通过JavaScript动态加载 -->
                    </div>
                    <div class="mt-6 flex justify-between items-center">
                        <div class="text-xl font-bold">
                            总计: <span id="cartTotal" class="text-blue-600">¥0</span>
                        </div>
                        <button onclick="createOrder()" 
                                class="bg-green-500 text-white px-6 py-2 rounded-lg hover:bg-green-600 transition-colors">
                            <i class="fas fa-check mr-2"></i>结算
                        </button>
                    </div>
                </div>
            </div>

            <!-- 订单管理页面 -->
            <div id="ordersPage" class="page-content hidden fade-in">
                <div class="flex justify-between items-center mb-6">
                    <div>
                        <h2 class="text-2xl font-bold text-gray-800">订单管理</h2>
                        <p class="text-gray-600 mt-1">管理所有订单信息</p>
                    </div>
                    <button onclick="showAddOrderModal()" class="btn-primary px-6 py-2 rounded-lg text-white flex items-center">
                        <i class="fas fa-plus mr-2"></i>
                        新建订单
                    </button>
                </div>
                <div class="bg-white rounded-xl shadow-sm overflow-hidden">
                    <div class="p-4 border-b">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center space-x-4">
                                <div class="relative">
                                    <input type="text" id="orderSearch" placeholder="搜索订单..." 
                                           onkeyup="filterOrders()"
                                           class="pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:border-indigo-500">
                                    <i class="fas fa-search absolute left-3 top-3 text-gray-400"></i>
                                </div>
                                <select id="orderStatusFilter" onchange="filterOrders()" 
                                        class="border rounded-lg px-4 py-2 focus:outline-none focus:border-indigo-500">
                                    <option value="all">所有状态</option>
                                    <option value="pending">待处理</option>
                                    <option value="processing">处理中</option>
                                    <option value="completed">已完成</option>
                                    <option value="cancelled">已取消</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <table class="min-w-full">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">订单号</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">总金额</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                            </tr>
                        </thead>
                        <tbody id="ordersTableBody" class="bg-white divide-y divide-gray-200">
                            <!-- 订单列表将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 新建/编辑订单模态框 -->
            <div id="orderModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden overflow-y-auto h-full w-full">
                <div class="relative top-20 mx-auto p-5 border w-2/3 shadow-lg rounded-md bg-white">
                    <div class="flex justify-between items-center border-b pb-3">
                        <h3 class="text-xl font-semibold" id="orderModalTitle">新建订单</h3>
                        <button onclick="closeOrderModal()" class="text-gray-500 hover:text-gray-700">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    <form id="orderForm" class="mt-4" onsubmit="handleOrderSubmit(event)">
                        <input type="hidden" id="orderId" name="id">
                        <div class="grid grid-cols-2 gap-4 mb-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700">订单状态</label>
                                <select id="orderStatus" name="status" required 
                                        class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                    <option value="pending">待处理</option>
                                    <option value="processing">处理中</option>
                                    <option value="completed">已完成</option>
                                    <option value="cancelled">已取消</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700">总金额</label>
                                <input type="number" id="orderAmount" name="total_amount" required step="0.01" min="0"
                                       class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                            </div>
                        </div>
                        <div class="border-t pt-4">
                            <h4 class="font-semibold mb-3">订单商品</h4>
                            <div id="orderItems" class="space-y-3">
                                <!-- 订单商品项将动态添加 -->
                            </div>
                            <button type="button" onclick="addOrderItem()" 
                                    class="mt-3 px-4 py-2 bg-gray-100 text-gray-700 rounded hover:bg-gray-200">
                                <i class="fas fa-plus mr-2"></i>添加商品
                            </button>
                        </div>
                        <div class="flex justify-end space-x-3 mt-5">
                            <button type="button" onclick="closeOrderModal()" 
                                    class="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300">
                                取消
                            </button>
                            <button type="submit" 
                                    class="px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700">
                                保存
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>

    <!-- 添加宠物模态框 -->
    <div id="addPetModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden overflow-y-auto h-full w-full">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
            <div class="mt-3">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">添加宠物</h3>
                <form id="addPetForm" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700">宠物名称</label>
                        <input type="text" name="name" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">宠物类型</label>
                        <select name="type" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                            <option value="">请选择类型</option>
                            <option value="dog">狗狗</option>
                            <option value="cat">猫咪</option>
                            <option value="bird">鸟类</option>
                            <option value="other">其他</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">年龄</label>
                        <input type="number" name="age" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">价格</label>
                        <input type="number" name="price" required step="0.01" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">描述</label>
                        <textarea name="description" rows="3" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"></textarea>
                    </div>
                    <div class="flex justify-end space-x-3 mt-5">
                        <button type="button" onclick="closeAddPetModal()" class="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-400">
                            取消
                        </button>
                        <button type="submit" class="px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500">
                            保存
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 编辑宠物模态框 -->
    <div id="editPetModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden overflow-y-auto h-full w-full">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
            <div class="mt-3">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">编辑宠物</h3>
                <form id="editPetForm" class="space-y-4">
                    <input type="hidden" name="id" id="editPetId">
                    <div>
                        <label class="block text-sm font-medium text-gray-700">宠物名称</label>
                        <input type="text" name="name" id="editPetName" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">宠物类型</label>
                        <select name="type" id="editPetType" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                            <option value="">请选择类型</option>
                            <option value="dog">狗狗</option>
                            <option value="cat">猫咪</option>
                            <option value="bird">鸟类</option>
                            <option value="other">其他</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">年龄</label>
                        <input type="number" name="age" id="editPetAge" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">价格</label>
                        <input type="number" name="price" id="editPetPrice" required step="0.01" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">描述</label>
                        <textarea name="description" id="editPetDescription" rows="3" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"></textarea>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">状态</label>
                        <select name="status" id="editPetStatus" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                            <option value="available">可用</option>
                            <option value="sold">已售出</option>
                            <option value="reserved">已预订</option>
                        </select>
                    </div>
                    <div class="flex justify-end space-x-3 mt-5">
                        <button type="button" onclick="closeEditPetModal()" class="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-400">
                            取消
                        </button>
                        <button type="submit" class="px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500">
                            保存
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let token = localStorage.getItem('token');
        const API_BASE_URL = 'http://localhost:3004/api';
        let localPets = [];
        let cartItems = [];
        let localOrders = [];

        // 初始化数据
        function initializeData() {
            try {
                localPets = JSON.parse(localStorage.getItem('localPets') || '[]');
                cartItems = JSON.parse(localStorage.getItem('cartItems') || '[]');
                localOrders = JSON.parse(localStorage.getItem('localOrders') || '[]');
                console.log('数据初始化成功', { localOrders });
            } catch (error) {
                console.error('数据初始化失败:', error);
                localPets = [];
                cartItems = [];
                localOrders = [];
            }
        }

        // 保存本地宠物数据
        function saveLocalPets() {
            localStorage.setItem('localPets', JSON.stringify(localPets));
        }

        // 保存购物车数据
        function saveCartItems() {
            localStorage.setItem('cartItems', JSON.stringify(cartItems));
        }

        // 保存订单数据
        function saveLocalOrders() {
            try {
                localStorage.setItem('localOrders', JSON.stringify(localOrders));
                console.log('订单数据保存成功', { localOrders });
            } catch (error) {
                console.error('保存订单数据失败:', error);
                alert('保存数据失败，请重试');
            }
        }

        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', () => {
            initializeData(); // 初始化所有数据
            checkAuth();
            setupEventListeners();
        });

        // 检查认证状态
        function checkAuth() {
            if (token) {
                showMainPage();
                loadDashboard();
            } else {
                showLoginPage();
            }
        }

        // 设置事件监听器
        function setupEventListeners() {
            // 退出登录
            document.getElementById('logoutBtn').addEventListener('click', handleLogout);

            // 导航项点击
            document.querySelectorAll('.nav-item').forEach(item => {
                item.addEventListener('click', (e) => {
                    e.preventDefault();
                    // 移除所有导航项的激活状态
                    document.querySelectorAll('.nav-item').forEach(nav => {
                        nav.classList.remove('active');
                        nav.classList.remove('bg-opacity-20');
                    });
                    // 添加当前点击项的激活状态
                    e.currentTarget.classList.add('active');
                    e.currentTarget.classList.add('bg-opacity-20');
                    const page = e.currentTarget.dataset.page;
                    showPage(page);
                });
            });

            // 添加宠物表单提交
            document.getElementById('addPetForm').addEventListener('submit', handleAddPet);

            // 编辑宠物表单提交
            document.getElementById('editPetForm').addEventListener('submit', handleEditPet);
        }

        // 处理登录
        async function handleLogin(event) {
            event.preventDefault();

            const usernameInput = document.getElementById('username');
            const passwordInput = document.getElementById('password');
            const username = usernameInput.value;
            const password = passwordInput.value;

            // Static login for testing: if username is '1', bypass API call
            if (username === '1') {
                console.log('Static login successful for user: 1');
                document.getElementById('loginPage').classList.add('hidden');
                document.getElementById('mainPage').classList.remove('hidden');
                // Assume static login bypasses auth check, directly set up UI
                setupEventListeners(); // Call this to set up event listeners for the main page
                loadDashboard(); // Load the default page (dashboard)
                return; // Stop further execution
            }

            try {
                const response = await fetch(`${API_BASE_URL}/users/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ username, password })
                });

                const data = await response.json();
                if (response.ok) {
                    token = data.token;
                    localStorage.setItem('token', token);
                    showMainPage();
                    loadDashboard();
                } else {
                    alert(data.error || '登录失败');
                }
            } catch (error) {
                alert('登录失败，请稍后重试');
            }
        }

        // 处理退出登录
        function handleLogout() {
            token = null;
            localStorage.removeItem('token');
            showLoginPage();
        }

        // 显示登录页面
        function showLoginPage() {
            document.getElementById('loginPage').classList.remove('hidden');
            document.getElementById('mainPage').classList.add('hidden');
        }

        // 显示主页面
        function showMainPage() {
            document.getElementById('loginPage').classList.add('hidden');
            document.getElementById('mainPage').classList.remove('hidden');
            showPage('dashboard');
        }

        // 显示特定页面
        function showPage(pageId) {
            document.querySelectorAll('.page-content').forEach(page => {
                page.classList.remove('active');
                page.classList.add('hidden');
            });
            const currentPage = document.getElementById(`${pageId}Page`);
            currentPage.classList.remove('hidden');
            currentPage.classList.add('active');
            loadPageData(pageId);
        }

        // 加载页面数据
        async function loadPageData(pageId) {
            switch (pageId) {
                case 'dashboard':
                    loadDashboard();
                    break;
                case 'pets':
                    loadPets();
                    break;
                case 'products':
                    loadProducts();
                    break;
                case 'cart':
                    loadCart();
                    break;
                case 'orders':
                    loadOrders();
                    break;
            }
        }

        // 加载控制台数据
        async function loadDashboard() {
            try {
                // 这里应该调用后端API获取统计数据
                const stats = {
                    orderCount: 150,
                    totalSales: 15000,
                    petCount: 45,
                    productCount: 200
                };

                // 更新显示
                document.querySelector('#dashboardPage .text-blue-600').textContent = stats.orderCount;
                document.querySelector('#dashboardPage .text-green-600').textContent = `¥${stats.totalSales}`;
                document.querySelector('#dashboardPage .text-purple-600').textContent = stats.petCount;
                document.querySelector('#dashboardPage .text-yellow-600').textContent = stats.productCount;
            } catch (error) {
                console.error('加载控制台数据失败:', error);
            }
        }

        // 加载宠物列表
        async function loadPets() {
            try {
                // 从本地存储加载数据
                localPets = JSON.parse(localStorage.getItem('localPets') || '[]');

                // 尝试从服务器获取最新数据
                const response = await fetch(`${API_BASE_URL}/pets`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (response.ok) {
                    const serverData = await response.json();
                    // 合并服务器数据，保留本地未同步的数据
                    const serverPetIds = new Set(serverData.map(p => p.id));
                    const localOnlyPets = localPets.filter(p => !serverPetIds.has(p.id));
                    localPets = [...localOnlyPets, ...serverData];
                    
                    // 保存到本地存储
                    saveLocalPets();
                }

                // 更新显示
                updatePetsTable();
            } catch (error) {
                console.error('加载宠物列表失败:', error);
                // 如果服务器请求失败，至少显示本地数据
                updatePetsTable();
            }
        }

        // 加载商品列表
        async function loadProducts() {
            try {
                const response = await fetch(`${API_BASE_URL}/products`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                const data = await response.json();
                
                const tbody = document.getElementById('productsTableBody');
                tbody.innerHTML = data.map(product => `
                    <tr>
                        <td class="px-6 py-4 whitespace-nowrap">${product.id}</td>
                        <td class="px-6 py-4 whitespace-nowrap">${product.name}</td>
                        <td class="px-6 py-4 whitespace-nowrap">¥${product.price}</td>
                        <td class="px-6 py-4 whitespace-nowrap">${product.stock}</td>
                        <td class="px-6 py-4 whitespace-nowrap">${product.status}</td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <button onclick="addToCart('pet', ${product.id})" class="text-blue-600 hover:text-blue-900">
                                加入购物车
                            </button>
                        </td>
                    </tr>
                `).join('');
            } catch (error) {
                console.error('加载商品列表失败:', error);
            }
        }

        // 加载购物车
        function loadCart() {
            const cartItemsContainer = document.getElementById('cartItems');
            if (!cartItems || cartItems.length === 0) {
                cartItemsContainer.innerHTML = '<div class="text-center text-gray-500 py-8">购物车是空的</div>';
                document.getElementById('cartTotal').textContent = '¥0.00';
                return;
            }

            cartItemsContainer.innerHTML = cartItems.map(item => `
                <div class="flex items-center justify-between border-b pb-4 mb-4">
                    <div class="flex-1">
                        <h3 class="font-semibold text-lg">${item.name}</h3>
                        <p class="text-gray-600">${item.description || '暂无描述'}</p>
                        <div class="flex items-center mt-2">
                            <button onclick="updateCartItemQuantity(${item.id}, -1)" 
                                    class="px-2 py-1 bg-gray-200 rounded-l hover:bg-gray-300">-</button>
                            <span class="px-4 py-1 bg-gray-100">${item.quantity}</span>
                            <button onclick="updateCartItemQuantity(${item.id}, 1)"
                                    class="px-2 py-1 bg-gray-200 rounded-r hover:bg-gray-300">+</button>
                        </div>
                    </div>
                    <div class="text-right ml-4">
                        <p class="font-bold text-lg">¥${(item.price * item.quantity).toFixed(2)}</p>
                        <button onclick="removeFromCart(${item.id})" 
                                class="text-red-600 hover:text-red-800 mt-2">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </div>
                </div>
            `).join('');

            // 更新总计
            const total = cartItems.reduce((sum, item) => sum + item.price * item.quantity, 0);
            document.getElementById('cartTotal').textContent = `¥${total.toFixed(2)}`;
        }

        // 加载订单列表
        function loadOrders() {
            try {
                // 重新从本地存储加载数据
                localOrders = JSON.parse(localStorage.getItem('localOrders') || '[]');
                console.log('加载订单数据', { localOrders });
                updateOrdersTable(localOrders);
            } catch (error) {
                console.error('加载订单列表失败:', error);
                alert('加载订单列表失败，请刷新页面重试');
            }
        }

        // 添加到购物车
        async function addToCart(type, id) {
            const pet = localPets.find(p => p.id === id);
            if (!pet) {
                alert('宠物信息不存在');
                return;
            }

            // 检查是否已在购物车中
            const existingItem = cartItems.find(item => item.id === id && item.type === 'pet');
            if (existingItem) {
                alert('该宠物已在购物车中');
                return;
            }

            // 检查宠物状态
            if (pet.status !== 'available') {
                alert('该宠物不可购买');
                return;
            }

            // 添加到购物车
            const cartItem = {
                id: pet.id,
                type: 'pet',
                name: pet.name,
                price: pet.price,
                quantity: 1,
                description: pet.description
            };

            cartItems.push(cartItem);
            saveCartItems();
            alert('已添加到购物车');

            // 更新购物车显示
            if (document.getElementById('cartPage').classList.contains('active')) {
                loadCart();
            }
        }

        // 从购物车中移除
        function removeFromCart(id) {
            cartItems = cartItems.filter(item => item.id !== id);
            saveCartItems();
            loadCart();
        }

        // 更新购物车商品数量
        function updateCartItemQuantity(id, change) {
            const item = cartItems.find(item => item.id === id);
            if (item) {
                item.quantity = Math.max(1, item.quantity + change);
                saveCartItems();
                loadCart();
            }
        }

        // 创建订单
        async function createOrder() {
            if (cartItems.length === 0) {
                alert('购物车是空的');
                return;
            }

            try {
                // 计算总金额
                const totalAmount = cartItems.reduce((sum, item) => sum + item.price * item.quantity, 0);

                // 创建订单数据
                const orderData = {
                    id: Date.now(), // 使用时间戳作为订单ID
                    items: [...cartItems],
                    total_amount: totalAmount,
                    status: 'pending',
                    created_at: new Date().toISOString()
                };

                // 更新宠物状态
                cartItems.forEach(item => {
                    if (item.type === 'pet') {
                        const pet = localPets.find(p => p.id === item.id);
                        if (pet) {
                            pet.status = 'sold';
                        }
                    }
                });
                saveLocalPets();

                // 保存订单
                localOrders.unshift(orderData);
                saveLocalOrders();

                // 清空购物车
                cartItems = [];
                saveCartItems();
                loadCart();

                // 显示成功消息
                alert('订单创建成功！');
                
                // 跳转到订单页面
                showPage('orders');
            } catch (error) {
                console.error('创建订单失败:', error);
                alert('创建订单失败，请稍后重试');
            }
        }

        // 查看订单详情
        function viewOrderDetails(orderId) {
            const order = localOrders.find(o => o.id === orderId);
            if (!order) {
                alert('订单不存在');
                return;
            }

            const detailsHtml = `
                <div class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full" id="orderDetailsModal">
                    <div class="relative top-20 mx-auto p-5 border w-3/4 shadow-lg rounded-md bg-white">
                        <div class="flex justify-between items-center border-b pb-3">
                            <h3 class="text-xl font-semibold">订单详情</h3>
                            <button onclick="closeOrderDetails()" class="text-gray-500 hover:text-gray-700">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        <div class="mt-4">
                            <div class="grid grid-cols-2 gap-4 mb-4">
                                <div>
                                    <p class="text-gray-600">订单编号</p>
                                    <p class="font-semibold">${order.id}</p>
                                </div>
                                <div>
                                    <p class="text-gray-600">创建时间</p>
                                    <p class="font-semibold">${new Date(order.created_at).toLocaleString()}</p>
                                </div>
                                <div>
                                    <p class="text-gray-600">订单状态</p>
                                    <p class="font-semibold">${
                                        order.status === 'pending' ? '待处理' :
                                        order.status === 'completed' ? '已完成' :
                                        order.status
                                    }</p>
                                </div>
                                <div>
                                    <p class="text-gray-600">订单总额</p>
                                    <p class="font-semibold text-blue-600">¥${order.total_amount.toFixed(2)}</p>
                                </div>
                            </div>
                            <div class="border-t pt-4">
                                <h4 class="font-semibold mb-3">订单商品</h4>
                                <div class="space-y-3">
                                    ${order.items.map(item => `
                                        <div class="flex justify-between items-center border-b pb-3">
                                            <div>
                                                <p class="font-semibold">${item.name}</p>
                                                <p class="text-sm text-gray-600">${item.description || '暂无描述'}</p>
                                            </div>
                                            <div class="text-right">
                                                <p class="font-semibold">¥${item.price.toFixed(2)} × ${item.quantity}</p>
                                                <p class="text-blue-600">¥${(item.price * item.quantity).toFixed(2)}</p>
                                            </div>
                                        </div>
                                    `).join('')}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;

            // 添加模态框到页面
            const modalContainer = document.createElement('div');
            modalContainer.innerHTML = detailsHtml;
            document.body.appendChild(modalContainer.firstChild);
        }

        // 关闭订单详情
        function closeOrderDetails() {
            const modal = document.getElementById('orderDetailsModal');
            if (modal) {
                modal.remove();
            }
        }

        // 显示添加宠物模态框
        function showAddPetModal() {
            document.getElementById('addPetModal').classList.remove('hidden');
            // 重置表单
            document.getElementById('addPetForm').reset();
        }

        // 关闭添加宠物模态框
        function closeAddPetModal() {
            document.getElementById('addPetModal').classList.add('hidden');
        }

        // 处理添加宠物
        async function handleAddPet(e) {
            e.preventDefault();
            const formData = new FormData(e.target);
            const petData = {
                id: new Date().getTime(), // 用时间戳作为临时ID
                name: formData.get('name'),
                type: formData.get('type'),
                age: parseInt(formData.get('age')),
                price: parseFloat(formData.get('price')),
                description: formData.get('description'),
                status: 'available',
                created_at: new Date().toISOString()
            };

            // 添加到本地存储
            localPets.unshift(petData);
            saveLocalPets();
            
            // 更新显示
            updatePetsTable();

            // 关闭模态框并重置表单
            closeAddPetModal();
            e.target.reset();

            // 显示成功消息
            alert('宠物添加成功');

            // 在后台尝试保存到数据库（不影响用户体验）
            try {
                const response = await fetch(`${API_BASE_URL}/pets`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(petData)
                });

                if (!response.ok) {
                    console.error('保存到数据库失败，但界面已更新');
                }
            } catch (error) {
                console.error('保存到数据库失败:', error);
            }
        }

        // 显示编辑宠物模态框
        function showEditPetModal(petId) {
            const pet = localPets.find(p => p.id === petId);
            if (!pet) return;

            document.getElementById('editPetId').value = pet.id;
            document.getElementById('editPetName').value = pet.name;
            document.getElementById('editPetType').value = pet.type;
            document.getElementById('editPetAge').value = pet.age;
            document.getElementById('editPetPrice').value = pet.price;
            document.getElementById('editPetDescription').value = pet.description;
            document.getElementById('editPetStatus').value = pet.status;

            document.getElementById('editPetModal').classList.remove('hidden');
        }

        // 关闭编辑宠物模态框
        function closeEditPetModal() {
            document.getElementById('editPetModal').classList.add('hidden');
        }

        // 处理编辑宠物
        async function handleEditPet(e) {
            e.preventDefault();
            const formData = new FormData(e.target);
            const petId = parseInt(formData.get('id'));
            const petData = {
                id: petId,
                name: formData.get('name'),
                type: formData.get('type'),
                age: parseInt(formData.get('age')),
                price: parseFloat(formData.get('price')),
                description: formData.get('description'),
                status: formData.get('status')
            };

            // 更新本地存储
            const index = localPets.findIndex(p => p.id === petId);
            if (index !== -1) {
                localPets[index] = { ...localPets[index], ...petData };
                saveLocalPets();
            }

            // 更新显示
            updatePetsTable();

            // 关闭模态框
            closeEditPetModal();

            // 显示成功消息
            alert('宠物信息更新成功');

            // 在后台尝试更新数据库
            try {
                const response = await fetch(`${API_BASE_URL}/pets/${petId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(petData)
                });

                if (!response.ok) {
                    console.error('更新数据库失败，但界面已更新');
                }
            } catch (error) {
                console.error('更新数据库失败:', error);
            }
        }

        // 删除宠物
        async function deletePet(petId) {
            if (!confirm('确定要删除这个宠物吗？')) {
                return;
            }

            try {
                // 从本地存储中删除
                localPets = localPets.filter(p => p.id !== petId);
                saveLocalPets();

                // 从购物车中移除相关项
                cartItems = cartItems.filter(item => !(item.type === 'pet' && item.id === petId));
                saveCartItems();

                // 更新显示
                updatePetsTable();
                
                // 如果当前在购物车页面，更新购物车显示
                if (document.getElementById('cartPage').classList.contains('active')) {
                    loadCart();
                }

                // 显示成功消息
                alert('宠物删除成功');

                // 在后台尝试从数据库中删除
                const response = await fetch(`${API_BASE_URL}/pets/${petId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (!response.ok) {
                    console.error('从数据库删除失败，但界面已更新');
                }
            } catch (error) {
                console.error('删除失败:', error);
            }
        }

        // 更新宠物表格显示
        function updatePetsTable() {
            const tbody = document.getElementById('petsTableBody');
            if (!localPets || localPets.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="6" class="px-6 py-4 text-center text-gray-500">
                            暂无宠物信息
                        </td>
                    </tr>
                `;
                return;
            }

            tbody.innerHTML = localPets.map(pet => `
                <tr class="hover:bg-gray-50">
                    <td class="px-6 py-4 whitespace-nowrap">${pet.id}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${pet.name}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${pet.type}</td>
                    <td class="px-6 py-4 whitespace-nowrap">¥${pet.price.toFixed(2)}</td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="px-2 py-1 rounded-full text-sm ${
                            pet.status === 'available' ? 'bg-green-100 text-green-800' :
                            pet.status === 'sold' ? 'bg-red-100 text-red-800' :
                            'bg-yellow-100 text-yellow-800'
                        }">
                            ${
                                pet.status === 'available' ? '可购买' :
                                pet.status === 'sold' ? '已售出' :
                                pet.status === 'reserved' ? '已预订' :
                                pet.status
                            }
                        </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap space-x-2">
                        ${pet.status === 'available' ? `
                            <button onclick="addToCart('pet', ${pet.id})" class="text-blue-600 hover:text-blue-900">
                                <i class="fas fa-cart-plus"></i>
                            </button>
                        ` : ''}
                        <button onclick="showEditPetModal(${pet.id})" class="text-yellow-600 hover:text-yellow-900">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button onclick="deletePet(${pet.id})" class="text-red-600 hover:text-red-900">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `).join('');
        }

        // 订单管理相关函数
        function showAddOrderModal() {
            document.getElementById('orderModalTitle').textContent = '新建订单';
            document.getElementById('orderForm').reset();
            document.getElementById('orderId').value = '';
            document.getElementById('orderItems').innerHTML = '';
            addOrderItem(); // 添加一个空的商品项
            document.getElementById('orderModal').classList.remove('hidden');
        }

        function showEditOrderModal(orderId) {
            const order = localOrders.find(o => o.id === orderId);
            if (!order) return;

            document.getElementById('orderModalTitle').textContent = '编辑订单';
            document.getElementById('orderId').value = order.id;
            document.getElementById('orderStatus').value = order.status;
            document.getElementById('orderAmount').value = order.total_amount;

            // 加载订单商品
            document.getElementById('orderItems').innerHTML = '';
            order.items.forEach(item => addOrderItem(item));

            document.getElementById('orderModal').classList.remove('hidden');
        }

        function closeOrderModal() {
            document.getElementById('orderModal').classList.add('hidden');
        }

        function addOrderItem(item = null) {
            const itemDiv = document.createElement('div');
            itemDiv.className = 'flex items-center space-x-4 border p-3 rounded';
            itemDiv.innerHTML = `
                <div class="flex-1">
                    <input type="text" name="itemName[]" placeholder="商品名称" required
                           value="${item ? item.name : ''}"
                           class="w-full px-3 py-2 border rounded">
                </div>
                <div class="w-32">
                    <input type="number" name="itemPrice[]" placeholder="价格" required step="0.01" min="0"
                           value="${item ? item.price : ''}"
                           class="w-full px-3 py-2 border rounded">
                </div>
                <div class="w-24">
                    <input type="number" name="itemQuantity[]" placeholder="数量" required min="1"
                           value="${item ? item.quantity : '1'}"
                           class="w-full px-3 py-2 border rounded">
                </div>
                <button type="button" onclick="this.parentElement.remove()" 
                        class="text-red-600 hover:text-red-800">
                    <i class="fas fa-trash"></i>
                </button>
            `;
            document.getElementById('orderItems').appendChild(itemDiv);
        }

        function handleOrderSubmit(e) {
            e.preventDefault();
            const formData = new FormData(e.target);
            const orderId = formData.get('id');
            
            // 收集商品项数据
            const items = [];
            const names = formData.getAll('itemName[]');
            const prices = formData.getAll('itemPrice[]');
            const quantities = formData.getAll('itemQuantity[]');
            
            for (let i = 0; i < names.length; i++) {
                items.push({
                    name: names[i],
                    price: parseFloat(prices[i]),
                    quantity: parseInt(quantities[i])
                });
            }

            // 创建订单数据
            const orderData = {
                id: orderId || Date.now(),
                status: formData.get('status'),
                total_amount: parseFloat(formData.get('total_amount')),
                items: items,
                created_at: orderId ? (localOrders.find(o => o.id === orderId)?.created_at || new Date().toISOString()) 
                                  : new Date().toISOString()
            };

            if (orderId) {
                // 更新现有订单
                const index = localOrders.findIndex(o => o.id === orderId);
                if (index !== -1) {
                    localOrders[index] = orderData;
                }
            } else {
                // 添加新订单
                localOrders.unshift(orderData);
            }

            saveLocalOrders();
            loadOrders();
            closeOrderModal();
            alert(orderId ? '订单更新成功' : '订单创建成功');
        }

        function deleteOrder(orderId) {
            console.log('开始删除订单', { orderId, beforeDelete: localOrders });
            
            if (!confirm('确定要删除这个订单吗？')) {
                return;
            }

            try {
                // 确保 orderId 是数字类型
                orderId = parseInt(orderId);
                
                // 重新从本地存储加载数据
                localOrders = JSON.parse(localStorage.getItem('localOrders') || '[]');
                
                // 过滤掉要删除的订单
                const originalLength = localOrders.length;
                localOrders = localOrders.filter(order => order.id !== orderId);
                
                // 检查是否真的删除了订单
                if (localOrders.length === originalLength) {
                    console.log('未找到要删除的订单', { orderId });
                    alert('删除失败：未找到订单');
                    return;
                }

                // 保存到本地存储
                localStorage.setItem('localOrders', JSON.stringify(localOrders));
                
                console.log('订单删除后', { afterDelete: localOrders });

                // 更新显示
                updateOrdersTable(localOrders);
                
                alert('订单删除成功');
            } catch (error) {
                console.error('删除订单失败:', error);
                alert('删除订单失败，请刷新页面后重试');
            }
        }

        function filterOrders() {
            const searchTerm = document.getElementById('orderSearch').value.toLowerCase();
            const statusFilter = document.getElementById('orderStatusFilter').value;

            const filteredOrders = localOrders.filter(order => {
                const matchesSearch = order.id.toString().includes(searchTerm) ||
                                    order.items.some(item => item.name.toLowerCase().includes(searchTerm));
                const matchesStatus = statusFilter === 'all' || order.status === statusFilter;
                return matchesSearch && matchesStatus;
            });

            updateOrdersTable(filteredOrders);
        }

        function updateOrdersTable(orders) {
            try {
                console.log('更新订单表格', { orders });
                const tbody = document.getElementById('ordersTableBody');
                if (!orders || orders.length === 0) {
                    tbody.innerHTML = `
                        <tr>
                            <td colspan="5" class="px-6 py-4 text-center text-gray-500">
                                暂无订单记录
                            </td>
                        </tr>
                    `;
                    return;
                }

                tbody.innerHTML = orders.map(order => `
                    <tr class="hover:bg-gray-50">
                        <td class="px-6 py-4 whitespace-nowrap">${order.id}</td>
                        <td class="px-6 py-4 whitespace-nowrap">${new Date(order.created_at).toLocaleString()}</td>
                        <td class="px-6 py-4 whitespace-nowrap">¥${order.total_amount.toFixed(2)}</td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 py-1 rounded-full text-sm ${
                                order.status === 'pending' ? 'bg-yellow-100 text-yellow-800' :
                                order.status === 'processing' ? 'bg-blue-100 text-blue-800' :
                                order.status === 'completed' ? 'bg-green-100 text-green-800' :
                                'bg-red-100 text-red-800'
                            }">
                                ${
                                    order.status === 'pending' ? '待处理' :
                                    order.status === 'processing' ? '处理中' :
                                    order.status === 'completed' ? '已完成' :
                                    '已取消'
                                }
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap space-x-2">
                            <button onclick="showEditOrderModal(${order.id})" 
                                    class="text-yellow-600 hover:text-yellow-900">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button onclick="deleteOrder(${order.id})" 
                                    class="text-red-600 hover:text-red-900">
                                <i class="fas fa-trash"></i>
                            </button>
                            <button onclick="viewOrderDetails(${order.id})" 
                                    class="text-blue-600 hover:text-blue-900">
                                <i class="fas fa-eye"></i>
                            </button>
                        </td>
                    </tr>
                `).join('');
            } catch (error) {
                console.error('更新订单表格失败:', error);
            }
        }
    </script>
</body>
</html>